package com.douguo.recipe;

import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;

import com.douguo.recipe.manager.AppRuntime;
import com.douguo.recipe.network.Constant;
import com.douguo.recipe.network.GetCachePhoto;
import com.douguo.recipe.network.GetHomeCategories;
import com.douguo.recipe.network.GetHomeRecipes2;
import com.douguo.recipe.network.Util;
import com.douguo.recipe.object.Caipin;
import com.douguo.recipe.object.Caipu;
import com.douguo.recipe.object.Caixi;
import com.douguo.recipe.object.HomeCategory;
import com.douguo.recipe.object.HomeRecipe;
import com.douguo.recipe.object.Kouwei;
import com.douguo.recipe.object.Sort;
import com.douguo.recipe.object.Tese;
import com.douguo.recipe.provider.DBHelper;
import com.douguo.recipe.view.NavigationView;
import com.exchange.Controller.ExchangeDataRequestListener;
import com.exchange.Controller.ExchangeDataService;
import com.exchange.Model.AdvertiserConfig;
import com.mobclick.android.MobclickAgent;

public class HomeActivity extends DouguoActivity {
	/** Called when the activity is first created. */
	private static final String TAG = "DouguoHome";

	// private Button[] mBtnCaixi = new Button[4];
	// private Button[] mBtnCaipin = new Button[2];
	// private Button mBtnKouwei;
	// private Button mBtnTese;
	// private HorizontalScrollView mScrollView;
	private TextView mTxNoRecipe;
	private LinearLayout mLlWait;
	private Gallery mGallery;
	private LinearLayout mGalleryPoints;
	private TextView mTvHotRecipe;
	private RelativeLayout mLayoutHotRecipes;
	// private GridView mGrid;
	// private LinearLayout mLinearLayout;

	private NavigationView mNavigation;

	private DBHelper mDBHelper;

	private DouguoApplication mDouguoApplication;

	private SimpleAdapter mAdapter;

	private List<Map<String, Object>> mRecipeList;

	private static final int MAX_RANDOM_RECIPELIST_NUMBER = 6;

	private static final int MENU_SETTING = Menu.FIRST;

	private static final int DIALOG_CONFIRM_EXIT = 0;

	private boolean isAutoDownloadThumb;
	private boolean isUseNetwork;

	private final static int MAX_RETRY_TIMES = 1;

	// -------------msg---------------
	public static final int MSG_HOME_RECIPES = 0;
	public static final int MSG_UPDATE = 1;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_UPDATE:
				MobclickAgent.update(HomeActivity.this);
				break;
			case MSG_HOME_RECIPES:
				List<HomeRecipe> recipes = (List<HomeRecipe>) msg.obj;
				// mScrollView.setVisibility(View.VISIBLE);

				mLlWait.setVisibility(View.GONE);
				mTxNoRecipe.setVisibility(View.GONE);
				if (recipes != null) {

					mDouguoApplication.getAppRuntime().put(
							Constant.GLOBAL_HOT_RECIPE, recipes);
					for (HomeRecipe caipu : recipes) {
						Map<String, Object> value = new HashMap<String, Object>();
						value.put("recipeName", caipu.getCaipu().name);
						// Bitmap bitmap = Util
						// .read80X80BitmapFromSDCard(caipu.picPath);
						Bitmap bitmap = BitmapFactory.decodeResource(
								getResources(), R.drawable.loading2);

						value.put("recipeImg", bitmap);
						value.put("recipeId", caipu.getCaipu().id);
						value.put("useNetwork", Boolean.TRUE);
						value.put("gettingImg", Boolean.FALSE);
						value.put("retry", 0);
						value.put("recipePicPath", caipu.getBanner());
						mRecipeList.add(value);
					}
					initGalleryPoints(recipes.size());
					mLayoutHotRecipes.setVisibility(View.VISIBLE);
				} else {
					if (!initDataFromDB()) {
						mLlWait.setVisibility(View.GONE);
						// mScrollView.setVisibility(View.GONE);
						mTxNoRecipe.setVisibility(View.VISIBLE);
					} else {
						mLayoutHotRecipes.setVisibility(View.VISIBLE);
					}
				}
				notifyDatasetChanged();
				break;
			case Constant.GET_PHOTO: {
				int pos = msg.arg1;
				SoftReference<Bitmap> refBitmap = (SoftReference<Bitmap>) msg.obj;
				Map<String, Object> hm = mRecipeList.get(pos);
				int retryTimes = (Integer) hm.get("retry");
				String thunmbPath = (String) hm.get("recipePicPath");
				if (refBitmap != null) {
					Bitmap bitmap = refBitmap.get();

					if (bitmap != null) {
						hm.put("recipeImg", bitmap);
						mAdapter.notifyDataSetChanged();
					} else {
						hm.put("retry", ++retryTimes);
						GetCachePhoto.getCachePhoto(pos, thunmbPath, mHandler);
					}

				} else if (refBitmap == null && retryTimes < MAX_RETRY_TIMES) {
					hm.put("retry", ++retryTimes);
					GetCachePhoto.getCachePhoto(pos, thunmbPath, mHandler);
				}

				break;
			}
			case Constant.MSG_HOT_CATEGORIES:// 获取热门分类
				mCategories = (List<HomeCategory>) msg.obj;
				mHotMenuProgressBar.setVisibility(View.GONE);
				if (mCategories == null || mCategories.size() == 0) {// 还是没有获取成功

					initHotMenuFromLocal();
				} else {
					mDouguoApplication.getAppRuntime().put(
							Constant.GLOBAL_HOT_MENU, mCategories);
					initHotMenu();
				}
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		mDouguoApplication = (DouguoApplication) getApplication();
		// MobclickAgent.update(this);
		mDBHelper = new DBHelper(this);
		isAutoDownloadThumb = Util.isDownloadPhotoPreferences(this);
		isUseNetwork = Util.isUseNetworkPreferences(this);
		initUI();
		initData();
		notifyDatasetChanged();
		mHandler.sendEmptyMessageDelayed(MSG_UPDATE, 2000);

		ExchangeDataService.requestDataAsyn(this,
				new ExchangeDataRequestListener() {
					@Override
					public void dataReceived(int status) {
						if (status == 0) {
							Log.i("exchange", "failed to get request data");
							((DouguoApplication)getApplication()).setYouMengExchange(false);
						} else {
							((DouguoApplication)getApplication()).setYouMengExchange(true);
						}
					}
				});
			
	}

	private void initData() {
		mRecipeList = new ArrayList<Map<String, Object>>();
		mAdapter = new HomeListAdapter(this, mRecipeList,
				R.layout.home_galleryitem, new String[] { /* "recipeName", */
				"recipeImg", "recipeId" }, new int[] {
				/* R.id.home_gallery_recipeName, */
				R.id.home_gallery_image });
		mAdapter.setViewBinder(new ViewBinder() {

			public boolean setViewValue(View view, Object data,
					String textRepresentation) {
				if (data instanceof String) {
					TextView tv = (TextView) view;
					tv.setText(textRepresentation);
				} else if (data instanceof Bitmap) {
					ImageView img = (ImageView) view;
					img.setImageBitmap((Bitmap) data);
					// img.setImageResource(R.drawable.gallery1);
				}
				return true;
			}
		});
		mGallery.setAdapter(mAdapter);
		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				if (position < mRecipeList.size()) {
					String title = (String) mRecipeList.get(position).get(
							"recipeName");
					mTvHotRecipe.setText(title);
					enableGalleryPoint(position);
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		// mGrid.setAdapter(mAdapter);
		if (isUseNetwork) {
			mLayoutHotRecipes.setVisibility(View.GONE);
			mLlWait.setVisibility(View.VISIBLE);
			// mScrollView.setVisibility(View.GONE);
			mTxNoRecipe.setVisibility(View.GONE);
			if (mAppRuntime.get(Constant.GLOBAL_HOT_RECIPE) == null) {
				GetHomeRecipes2.getHomeCaipuList(mHandler);// 获取热门菜谱
			} else {
				mHandler.sendMessage(Message.obtain(mHandler, MSG_HOME_RECIPES,
						mAppRuntime.get(Constant.GLOBAL_HOT_RECIPE)));
			}
			if (mAppRuntime.get(Constant.GLOBAL_HOT_MENU) == null) {
				GetHomeCategories.getHomeCategories(mHandler);// 获取推荐分类
			} else {
				mHandler.sendMessage(Message.obtain(mHandler,
						Constant.MSG_HOT_CATEGORIES,
						mAppRuntime.get(Constant.GLOBAL_HOT_MENU)));
			}
		} else {
			if (!initDataFromDB()) {
				mLlWait.setVisibility(View.GONE);
				// mScrollView.setVisibility(View.GONE);
				mTxNoRecipe.setVisibility(View.VISIBLE);

			}
		}
	}

	private boolean initDataFromDB() {
		List<Caipu> recipes = mDBHelper
				.getRandomCaipuList(MAX_RANDOM_RECIPELIST_NUMBER);
		if (recipes.size() <= 0)
			return false;
		for (Caipu caipu : recipes) {
			Map<String, Object> value = new HashMap<String, Object>();
			value.put("recipeName", caipu.name);
			Bitmap bitmap = Util.read80X80BitmapFromSDCard(caipu.thumbPath);
			if (bitmap == null) {
				bitmap = BitmapFactory.decodeResource(getResources(),
						R.drawable.cookdefault80);
			}
			value.put("recipeImg", bitmap);
			value.put("recipeId", caipu.id);
			mRecipeList.add(value);
		}
		initGalleryPoints(recipes.size());
		initHotMenuFromLocal();
		return true;
	}

	private void notifyDatasetChanged() {
		if (mAdapter != null) {
			mAdapter.notifyDataSetChanged();
		}
	}

	private AppRuntime mAppRuntime = AppRuntime.getInstance();
	private List<HomeCategory> mCategories;
	private LinearLayout mLinearlayoutHotMenu;

	private void startRecipeListActivity(Sort sort, String title) {
		Bundle bundle = new Bundle();
		Intent intent = new Intent(this, RecipelistActivity.class);
		int type = Constant.TYPE_CAIXI;
		if (sort instanceof Caixi) {
			type = Constant.TYPE_CAIXI;
		} else if (sort instanceof Caipin) {
			type = Constant.TYPE_CAIPIN;
		} else if (sort instanceof Tese) {
			type = Constant.TYPE_TESE;
		} else if (sort instanceof Kouwei) {
			type = Constant.TYPE_KOUWEI;
		}
		bundle.putString("title", title);
		bundle.putIntArray("types", new int[] { type });
		bundle.putStringArray("ids", new String[] { sort.id });
		intent.putExtras(bundle);
		startActivity(intent);
	}

	private void addHotMenu(final HomeCategory categorie) {
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.ihot_menu_btn, null);
		TextView textview = (TextView) view.findViewById(R.id.hot_menu_text);
		ImageView imageview = (ImageView) view.findViewById(R.id.hot_menu_pic);
		textview.setText(categorie.title);
		int resId = getResources().getIdentifier(categorie.icon, "drawable",
				"com.douguo.recipe");
		if (resId != 0) {
			imageview.setImageResource(resId);
		}
		view.findViewById(R.id.hot_menu_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						startRecipeListActivity(categorie.sort, categorie.title);
					}
				});
		mLinearlayoutHotMenu.addView(view);
	}

	private HomeCategory convertSortToHomeCategory(Sort sort) {
		HomeCategory category = new HomeCategory();
		category.title = sort.name;
		category.sort = sort;
		category.icon = "shanghaicai";
		if (sort instanceof Caixi) {
			category.icon = "shanghaicai";
		} else if (sort instanceof Caipin) {
			category.icon = "douzhipin";
		} else if (sort instanceof Tese) {
			category.icon = "jicai";
		} else if (sort instanceof Kouwei) {
			category.icon = "mincai";
		}
		return category;
	}

	private void initHotMenuFromLocal() {
		mHotMenuProgressBar.setVisibility(View.GONE);
		mLinearlayoutHotMenu.removeAllViews();
		List<Sort> caixis = mDBHelper.getRandomSort(new Caixi("1", "1"), 1);
		if (caixis != null && caixis.size() > 0) {
			HomeCategory category = convertSortToHomeCategory(caixis.get(0));
			addHotMenu(category);
		}

		List<Sort> caipins = mDBHelper.getRandomSort(new Caipin("1", "1"), 1);
		if (caipins != null && caipins.size() > 0) {
			HomeCategory category = convertSortToHomeCategory(caipins.get(0));
			addHotMenu(category);
		}

		List<Sort> teses = mDBHelper.getRandomSort(new Tese("1", "1"), 1);
		if (teses != null && teses.size() > 0) {
			HomeCategory category = convertSortToHomeCategory(teses.get(0));
			addHotMenu(category);
		}
		List<Sort> kouweis = mDBHelper.getRandomSort(new Kouwei("1", "1"), 1);
		if (kouweis != null && kouweis.size() > 0) {
			HomeCategory category = convertSortToHomeCategory(kouweis.get(0));
			addHotMenu(category);
		}
	}

	private void initHotMenu() {
		// mLinearlayoutHotMenu =
		// (LinearLayout)findViewById(R.id.home_hot_menu);
		if (mCategories != null) {// 热门分类已经获取成功
			Log.d(TAG, "initHotMenu");
			mLinearlayoutHotMenu.removeAllViews();
			for (int i = 0; i < mCategories.size()
					&& i < Constant.MAX_HOME_GALLERY_NUMBER; i++) {
				addHotMenu(mCategories.get(i));
			}
		}
		// else {//热门分类未获取，先尝试再次获取，获取失败后显示本地分类
		//
		//
		// }
	}

	private ProgressBar mHotMenuProgressBar;

	private void initUI() {
		mLinearlayoutHotMenu = (LinearLayout) findViewById(R.id.home_hot_menu);
		mTvHotRecipe = (TextView) findViewById(R.id.home_hot_recipe_name);
		mTxNoRecipe = (TextView) findViewById(R.id.no_home_recipe);
		mLlWait = (LinearLayout) findViewById(R.id.home_wait);
		mGallery = (Gallery) findViewById(R.id.home_gallery);
		mGallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(HomeActivity.this,
						RecipeActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("recipeId", (String) mRecipeList.get(position)
						.get("recipeId"));
				bundle.putInt("pos", position);
				int[] ids = null;
				ids = new int[mRecipeList.size()];
				int i = 0;
				for (Map recipe : mRecipeList) {
					ids[i++] = Integer.valueOf((String) recipe.get("recipeId"));
				}
				bundle.putIntArray("ids", ids);
				intent.putExtras(bundle);
				startActivity(intent);

			}
		});
		mLayoutHotRecipes = (RelativeLayout) findViewById(R.id.home_hot_recipes_layout);

		mGalleryPoints = (LinearLayout) findViewById(R.id.home_gallery_point_layout);
		mHotMenuProgressBar = (ProgressBar) findViewById(R.id.home_hot_menu_progress);

		mHotMenuProgressBar.setVisibility(View.VISIBLE);

		mNavigation = new NavigationView(this, NavigationView.STATE_HOME);

		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showDialog(DIALOG_CONFIRM_EXIT);
			return true;
		}
		return false;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_CONFIRM_EXIT:
			return new AlertDialog.Builder(HomeActivity.this)
					.setTitle(R.string.confirmExit)
					.setPositiveButton(R.string.confirm,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									finish();
									/* User clicked OK so do some stuff */
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked Cancel so do some stuff */
								}
							}).create();
		}
		return null;

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_SETTING, 0, R.string.setting);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_SETTING:
			startActivity(new Intent(this, SettingActivity.class));
			break;
		}
		return true;

	}

	private void initGalleryPoints(int number) {
		for (int i = 0; i < number; i++) {
			ImageView imgView = new ImageView(this);
			imgView.setImageResource(R.drawable.unselect_circle);
			imgView.setPadding(10, 0, 0, 0);
			mGalleryPoints.addView(imgView);
		}
		if (number > 0) {
			enableGalleryPoint(0);
		}
	}

	private void enableGalleryPoint(int position) {
		for (int i = 0; i < mGalleryPoints.getChildCount(); i++) {
			ImageView imgView = (ImageView) mGalleryPoints.getChildAt(i);
			if (position == i) {

				imgView.setImageResource(R.drawable.selected_circle);
			} else {
				imgView.setImageResource(R.drawable.unselect_circle);
			}
		}
	}

	private class RecycleAdapter extends SimpleAdapter {

		private List<? extends Map<String, ?>> mData;

		public RecycleAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			super(context, data, resource, from, to);
			mData = data;
			// TODO Auto-generated constructor stub
		}

		public int getCount() {
			if (mData.size() <= 1)
				return mData.size();
			return Integer.MAX_VALUE;
		}

		public Object getItem(int position) {
			position = position % mData.size();
			if (position < 0)
				position = position + mData.size();
			return position;
		}

		public long getItemId(int position) {
			position = position % mData.size();
			if (position < 0)
				position = position + mData.size();
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (mData.size() != 0) {
				position = position % mData.size();
				if (position < 0)
					position = position + mData.size();
			}
			return super.getView(position, convertView, parent);
		}
	}

	private class HomeListAdapter extends SimpleAdapter {

		public HomeListAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			super(context, data, resource, from, to);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			Map map = (Map) getItem(position);
			if (isAutoDownloadThumb
					&& map.containsKey("useNetwork")
					&& map.get("useNetwork") == Boolean.TRUE
					&& (!map.containsKey("gettingImg") || map.get("gettingImg") == Boolean.FALSE)) {
				GetCachePhoto.getCachePhoto(position,
						(String) map.get("recipePicPath"), mHandler);

				map.put("gettingImg", Boolean.TRUE);
			}
			return view;
		}

	}

}